﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace NetfractionHub.Network.Protocol
{
	public class ProtocolParameter
	{
		private string _parameterValue;

		public ProtocolParameter(string parameterCode, string parameterValue)
		{
			this.ParameterCode = string.Empty;
			_parameterValue = string.Empty;
			if (parameterCode.Length == 2)
			{
				//if (Regex.IsMatch(parameterCode.Substring(0, 1), "[A-Z]") && Regex.IsMatch(parameterCode.Substring(1, 1), "[A-Z0-9]"))
				if (Char.IsLetter(parameterCode[0]) && Char.IsLetterOrDigit(parameterCode[1]))
				{
					this.ParameterCode = parameterCode;
					_parameterValue = parameterValue;
				}
				else
				{
					throw new ArgumentException("Invalid params in ProtocolParameter");
				}
			}
		}

		public ProtocolParameter(string parameterValue)
		{
			_parameterValue = parameterValue;
			this.ParameterCode = string.Empty;
		}

		public static ProtocolParameter Split(ProtocolParameter parameter, string parameterCode)
		{
			if (parameter.ParameterValue.Length >= 2 && parameterCode.Length == 2 && parameter.ParameterValue.StartsWith(parameterCode, StringComparison.Ordinal))
				return new ProtocolParameter(parameter.ParameterValue.Substring(0, 2), parameter.ParameterValue.Substring(2));

			return parameter;
		}

		private string EscapeParameterValue(string value)
		{
			return value.Replace(@"\\", @"\\").Replace(@" ", @"\s").Replace("\n", @"\n");
		}

		private static string UnEscapeParameterValue(string value)
		{
			return value.Replace(@"\s", @" ").Replace(@"\n", "\n").Replace(@"\\", @"\\");
		}

		public override string ToString()
		{
			return (string.IsNullOrEmpty(this.ParameterCode) ? EscapeParameterValue(_parameterValue) : this.ParameterCode + EscapeParameterValue(_parameterValue));
		}

		public string ParameterCode { get; set; }

		public string ParameterValue
		{
			get { return UnEscapeParameterValue(_parameterValue); }
			set { _parameterValue = value; }
		}
	}
}
